import os
import json
import shutil
import win32api
import win32print
import random
import string
from copy import deepcopy
import re
import time
import datetime
import tkinter as tk
from docx import Document
import requests
from multiprocessing.dummy import Pool
from lxml import etree
import pyperclip
import windnd

r"""
pyinstaller -D -w -i .\1.ico shift_rec.py

"""


# 自定义无信息异常
class NoInfoError(Exception):
    pass


def print_file(filename):
    win32api.ShellExecute(
        0,
        'print',
        filename,
        '/d:"%s"' % win32print.GetDefaultPrinter(),
        '.',
        0)


class AcquireInfoTotal(object):
    def __init__(self, pid):
        self.pid = pid
        get_params = {'id': str(pid)}

        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"
        }

        url_get = "http://10.68.1.38:8000/doqleiview/doqleiview.aspx"

        self.users = requests.Session()

        get_basic_content = self.users.get(url_get, params=get_params, headers=self.headers)

        self.basic_html_doc = get_basic_content.text

        basic_tree = etree.HTML(self.basic_html_doc)

        self.basic_param_patient = basic_tree.xpath('//ul[@class="ztree"]')[0].attrib
        basic_param_code = basic_tree.xpath('//div[contains(@class, "model_menu_items")]')[0].attrib
        post_param_menu = {
            'type': self.basic_param_patient['data-type'],
            'mdata': self.basic_param_patient['data-mdata'],
            'integrationim': self.basic_param_patient['data-integrationim'],
            'inum': self.basic_param_patient['data-inum'],
            'idata[0].key': 'uhid',
            'idata[0].value': basic_param_code["data-uhid"],
            'idata[1].key': 'date_validated',
            'idata[1].value': self.basic_param_patient['data-date_validated'],
            'idata[2].key': 'treatment',
            'idata[2].value': basic_param_code["data-uhid"].split(']')[1],
        }
        url_menu = "http://10.68.1.38:8000/Menu/MedicalMenu"

        self.menu_json_data = self.users.post(
            url_menu,
            headers=self.headers,
            data=post_param_menu
        )

    def query_content(self, query_kind='病程记录'):
        menu_respond = self.menu_json_data.json()
        test_info_data = {}
        for i in menu_respond['Data']:

            test_info_data.update(i.setdefault('Data', {}))

            if i.setdefault('Text', '') == query_kind:
                mtype = i['Type']
                break
            if i.setdefault('Children', ''):
                for j in i['Children']:
                    test_info_data.update(j.setdefault('Data', {}))
                    if j.setdefault('Text', '') == query_kind:
                        mtype = j['Type']

                        break
                else:
                    continue
                break

        post_para_test = {
            'type': self.basic_param_patient['data-type'],
            'patientid': '☆',
            'snick': '',
            'mdata': self.basic_param_patient['data-mdata'],
            'integrationim': self.basic_param_patient['data-integrationim'],
            'inum': self.basic_param_patient['data-inum'],
            'patientname': self.basic_param_patient['data-patientname'],
            'official1': self.basic_param_patient['data-official1'],
            'mtype': mtype,
        }

        index_ = 0
        for k, v in test_info_data.items():
            post_para_test['idata[%s].key' % index_] = k
            post_para_test['idata[%s].value' % index_] = v
            index_ += 1

        url_result = "http://10.68.1.38:8000/Content/Index"

        result = self.users.post(
            url_result,
            headers=self.headers,
            data=post_para_test
        ).text

        return {query_kind: result}


class DataResolver(object):
    def __init__(self, pid):
        self.patient_info = {}
        self.pid = pid

    @staticmethod
    def do_table(html_grab):
        tree = etree.HTML(html_grab)
        tables = tree.xpath('//table')
        result_list = []
        for table in tables:
            table_dic = {}
            trs = table.findall('.//tr')
            table_dic['test_title'] = trs[0].find('.//td//input').attrib.get('value').split('(')[0]
            test_date = trs[0].find('.//td//input').attrib.get('value').split('(')[1]
            test_date = test_date.strip()
            test_date = test_date.strip(':')
            test_date = test_date.strip(')')
            table_dic['test_date'] = test_date
            table_dic['test_result'] = []
            for tr in trs[2:]:
                tds = tr.findall('.//td')
                result_details = {
                    'title': tds[1].text,
                    'result': tds[2].text.strip(),
                    'note': tds[3].find('./font').text,
                    'flag': '升高' if tds[3].find('./font').text == '↑' else (
                        '降低' if tds[3].find('./font').text == '↓' else '正常')
                }

                table_dic['test_result'].append(result_details)
            result_list.append(table_dic)
        return result_list

    @staticmethod
    def do_test(test_result):
        result_dic = {}
        with open('.\\myjson\\spliter.json', 'r', encoding='utf-8') as load_f:
            load_dic = json.load(load_f)

        for each_test_dic in test_result:

            for k_test in load_dic.keys():
                if k_test in each_test_dic["test_title"]:
                    for each_test_result in each_test_dic["test_result"]:
                        if k_test not in result_dic.keys():
                            result_dic[k_test] = {}
                        if each_test_dic["test_date"] not in result_dic[k_test].keys():
                            result_dic[k_test][each_test_dic["test_date"]] = []

                        for each_test_key in load_dic[k_test].keys():
                            if each_test_key in each_test_result["title"]:
                                if each_test_result["flag"] in load_dic[k_test][each_test_key].keys():
                                    result_dic[k_test][each_test_dic["test_date"]].append(
                                        {
                                            "项目": each_test_result["title"],
                                            "结果": "%s %s" % (each_test_result["result"],
                                                             load_dic[k_test][each_test_key]["单位"]),
                                            "提示": load_dic[k_test][each_test_key][each_test_result["flag"]]
                                        })

        with open('.\\myjson\\test_analysis.json', 'r', encoding='utf-8') as load_f:
            test_load = json.load(load_f)
        for each_test_dic in test_result:

            for k_test in test_load.keys():
                if k_test in each_test_dic["test_title"]:
                    for each_test_result in each_test_dic["test_result"]:
                        if k_test not in result_dic.keys():
                            result_dic[k_test] = {}
                        if each_test_dic["test_date"] not in result_dic[k_test].keys():
                            result_dic[k_test][each_test_dic["test_date"]] = []

                        for each_test_key_analysis in test_load[k_test].keys():
                            if each_test_key_analysis in each_test_result["title"]:

                                if each_test_result["result"] != test_load[k_test][each_test_key_analysis]:
                                    result_dic[k_test][each_test_dic["test_date"]].append(
                                        {
                                            "项目": each_test_result["title"],
                                            "结果": each_test_result["result"],
                                            "提示": ""
                                        })

        result_string = '入院根据当前疫情防控及上级文件要求：查新型冠状病毒核酸检测示阴性。'
        for each_test_kind, each_test_kind_v in result_dic.items():

            result_string += '查%s：' % each_test_kind

            for index_v, data_v in enumerate(each_test_kind_v.values()):
                if data_v:
                    if index_v > 0:
                        result_string += '查%s：' % each_test_kind
                    normal = True

                    for each_data_dict in data_v:

                        result_string += '%s：%s ' % (each_data_dict['项目'], each_data_dict['结果'])
                        if each_data_dict['提示']:
                            normal = False
                            result_string += '提示：%s' % each_data_dict['提示']
                    if normal and each_test_kind in load_dic.keys():
                        result_string += '未见明显异常。'
                else:
                    result_string += "未见异常。"

        return result_string

    def record_resolve(self, html_dic):
        tree = etree.HTML(html_dic['病程记录'])
        basic_info_td = tree.xpath('//div[@esttype="入院记录"]//table')[0].xpath('.//td//text()') if tree.xpath('//div[@esttype="入院记录"]//table') else []
        for i in basic_info_td:
            i = i.strip()
            if i:
                info_list = i.split("：")
                self.patient_info[info_list[0]] = info_list[1]

        self.patient_info["住院号"] = str(self.pid)
        self.patient_info["入院日期"] = self.patient_info.setdefault('入院时间', '无信息').split()[0]
        self.patient_info["主诉"] = tree.xpath('//span[@itemid="5"]')[0].text if tree.xpath('//span[@itemid="5"]') else '无信息'
        self.patient_info["诊断"] = tree.xpath('//span[@itemid="8"]')[0].xpath('string(.)').split()[1] if tree.xpath('//span[@itemid="8"]') else '无信息'
        self.patient_info["现病史"] = tree.xpath('//span[@itemid="6"]')[0].text if tree.xpath('//span[@itemid="6"]') else "无信息"
        self.patient_info["TPRBP"] = tree.xpath('//span[@itemid="10"]')[0].text if tree.xpath('//span[@itemid="10"]') else "无信息"
        self.patient_info["入院体检"] = tree.xpath('//p[@class="childmouseover"]')[0].xpath('string(.)').strip() if tree.xpath('//p[@class="childmouseover"]') else "无信息"
        self.patient_info["入院化验单"] = \
            tree.xpath('//p[@class="childmouseover"]/following-sibling::p/following-sibling::p//text()')[0] if tree.xpath('//p[@class="childmouseover"]/following-sibling::p/following-sibling::p//text()') else "无信息"
        self.patient_info["病人简介"] = tree.xpath('//span[@itemid="1"]')[0].text if tree.xpath('//span[@itemid="1"]') else "无信息"
        first_info_p = tree.xpath('//div[@esttype="首次病程记录"]//p')[1].xpath('string(.)').strip() if tree.xpath('//div[@esttype="首次病程记录"]//p') else '无信息'
        content_1 = re.findall(r".+病例特点：1(\.|、)(.+?)2(\.|、)(查体|体格检查).+?", first_info_p)
        if content_1:
            self.patient_info['病例特点'] = content_1[0][1]
        content_2 = re.findall(r".+诊疗计划：1(\.|、)(.+)2(\.|、)(.+)3(\.|、)(.+)4(\.|、)(.+)\d?", first_info_p)
        if content_2:
            self.patient_info['诊疗计划'] = content_2[0][1::2]

        lis_data = html_dic.setdefault('LIS报告单', '')
        if lis_data:
            result_lis = self.do_table(lis_data)

            result_lis = self.do_test(result_lis)

            self.patient_info['化验单'] = result_lis

        return self.patient_info


def to_word(result_json):
    # 将获取的信息存为word文档以便打印 2021年2月01日 19 时 00 分至2021年2月2日08 时 00 分
    cur_date = datetime.datetime.strftime(datetime.datetime.today(), "%Y{}%m{}%d{}").format("年", "月", "日")
    one_day = datetime.timedelta(days=1)
    past_date = datetime.datetime.strftime(datetime.datetime.today() - one_day, "%Y{}%m{}%d{}").format("年", "月", "日")

    cur_hour = int(time.strftime("%H", time.localtime()))
    if cur_hour >= 12:

        time_string = "%s 08时00分至%s 19时00分" % (cur_date, cur_date)
    else:
        time_string = "%s 19时00分至%s 08时00分" % (past_date, cur_date)
    patient_statistic = "原住院人数29 人、入院 %s人、转入 0 人、转出 0 人、出院 0 人、手术 0 人、操作 0人、抢救 0 人、病危（病重） 0 人、死亡 0 人、危急值 0 人、输血 0 人、现住院人数30 人。"

    if os.path.isfile('.\\mydocx\\shift_mod_done.docx'):
        os.remove('.\\mydocx\\shift_mod_done.docx')

    shift_mod = Document(".\\mydocx\\shift.docx")

    t = shift_mod.tables[0]
    t.rows[0].cells[1].text = time_string

    if len(result_json) > 1:
        flag = True
    else:
        flag = False

    for k, v in result_json.items():
        if flag:
            new_row = deepcopy(t.rows[-3])
            t.rows[-2]._tr.addprevious(new_row._element)
        t.rows[-4].cells[0].text = v['床号']
        t.rows[-4].cells[1].text = v['姓名']
        t.rows[-4].cells[2].text = v['性别']
        t.rows[-4].cells[3].text = v['年龄']
        t.rows[-4].cells[4].text = '新入'
        t.rows[-4].cells[5].text = '%s 患儿以%s为代主诉入院 查体：%s 初步诊断：%s 入院后给予%s 下班密切注意患儿' % (
            v['入院时间'].split()[1],
            v['主诉'],
            v['入院体检'],
            v['诊断'],
            v['诊疗计划'][1],
        )

    t.rows[1].cells[1].text = patient_statistic % (str(len(result_json)))
    # 删除倒数第三行
    t.rows[-3]._element.getparent().remove(t.rows[-3]._element)
    if not os.path.exists('temp'):
        os.mkdir('temp')
    random_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))

    shift_mod.save('.\\temp\\%s.docx' % random_file_name)
    os.startfile('.\\temp\\%s.docx' % random_file_name)


def save_to_word(text_info):
    date_to_write = text_info['入院时间'].split()[0]
    d = Document('.\\mydocx\\a_notification.docx')

    # 获取word文档内的表格列表
    t = d.tables
    # 第一个表格为病人基本信息，包括姓名、性别、年龄
    t1 = t[0]

    # 姓名值位于t1.cell(0, 1)，即第一行第2列；
    run = t1.cell(0, 1).paragraphs[0].add_run(text_info['姓名'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 性别值位于t1.cell(0, 3)，即第一行第4列；
    run = t1.cell(0, 4).paragraphs[0].add_run(text_info['性别'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 年龄值位于t1.cell(0, 5)，即第一行第6列；
    run = t1.cell(0, 6).paragraphs[0].add_run(text_info['年龄'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 身份证号
    run = t1.cell(1, 1).paragraphs[0].add_run(text_info['身份证明号'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 住院号
    run = t1.cell(2, 1).paragraphs[0].add_run(text_info['住院号'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 诊断
    run = t1.cell(2, 4).paragraphs[0].add_run(text_info['诊断'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 入院时间
    run = t1.cell(3, 4).paragraphs[0].add_run(date_to_write)
    run.font.name = '宋体'
    run.font.size = 140000
    # 时间1
    run = t1.cell(6, 5).paragraphs[0].add_run(date_to_write)
    run.font.name = '宋体'
    run.font.size = 140000
    # 时间2
    run = t1.cell(8, 3).paragraphs[0].add_run(date_to_write)
    run.font.name = '宋体'
    run.font.size = 140000
    if not os.path.exists('temp'):
        os.mkdir('temp')
    random_file_name1 = ''.join(random.sample(string.ascii_letters + string.digits, 8))

    d.save('.\\temp\\%s.docx' % random_file_name1)
    # 调试
    # os.startfile(os.path.abspath('.\\temp\\%s.docx' % random_file_name1))
    print_file(os.path.abspath('.\\temp\\%s.docx' % random_file_name1))
    random_file_name2 = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    d.save('.\\temp\\%s.docx' % random_file_name2)
    print_file(os.path.abspath('.\\temp\\%s.docx' % random_file_name2))


def in_and_out(result_json):
    in_and_out_mod = Document(".\\mydocx\\in_and_out.docx")

    t = in_and_out_mod.tables[0]

    contents = ['住院号', '姓名', '性别', '年龄', '医师', '入院情况', '出院诊断', '入院日期', '出院日期',
                '治疗效果', '联系人地址', '联系人电话']
    for k, v in result_json.items():

        t.add_row()
        for idx, kys in enumerate(contents):

            if kys == '治疗效果':
                t.rows[-1].cells[idx].text = '治愈'
            else:
                t.rows[-1].cells[idx].text = v.setdefaut(kys, '无信息').strip()

    if not os.path.exists('出入院登记本'):
        os.mkdir('出入院登记本')
    random_file_name = time.strftime('%Y-%m-%d_%H%M%S', time.localtime())

    in_and_out_mod.save('.\\出入院登记本\\%s.docx' % random_file_name)
    os.startfile('.\\出入院登记本\\%s.docx' % random_file_name)


class DifDiagnosis(tk.Toplevel):
    def __init__(self):

        super().__init__()
        self.wm_attributes('-topmost', 1)

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 550
        wh = 400
        self.geometry(
            "%dx%d+%d+%d" %
            (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('鉴别诊断')
        tk.Label(self, text='鉴别诊断').grid(sticky="w" + "e")
        with open('.\\myjson\\dif_diagnosis.json', 'r', encoding='utf-8') as f:
            dif_diagnosis = json.load(f)

        self.curriculum = dif_diagnosis
        self.var = {}
        row_idx = 1
        col_idx = 0
        for k, v in self.curriculum.items():
            self.var[k] = tk.BooleanVar()
            tk.Checkbutton(self, text=k, variable=self.var[k]).grid(row=row_idx, column=col_idx, sticky="w")
            col_idx += 1
            if col_idx > 3:
                row_idx += 1
                col_idx = 0
        btn_frame = tk.Frame(self)
        btn_frame.grid(row=row_idx + 1, columnspan=5)
        tk.Button(btn_frame, text='确认', command=self.confirm, width=12, height=1, activebackground='grey',
                  relief='groove').grid(row=row_idx + 1, column=0, columnspan=2)

        tk.Button(btn_frame, text='退出', command=self.cancel, width=12, height=1, activebackground='grey',
                  relief='groove').grid(row=row_idx + 1, column=3, columnspan=2)

    def cancel(self):
        self.destroy()

    def confirm(self):
        select = ''
        idx = 1
        for k, v in self.var.items():
            if v.get():
                select += '%d.%s：%s;' % (idx, k, self.curriculum[k])
                idx += 1
        pyperclip.copy(select)
        self.destroy()


# 图形界面
class PatientInfo(tk.Toplevel):
    def __init__(self, patient_info):
        self.patient_info = patient_info
        super().__init__()
        self.wm_attributes('-topmost', 1)

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 400
        wh = 850
        self.geometry(
            "%dx%d+%d+%d" %
            (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('病人信息')
        tk.Label(self, text='%s %s' % (patient_info['姓名'], patient_info['住院号'])).pack()
        self.flag = tk.StringVar()
        self.flag.set('姓名')
        radio_frame = tk.Frame(self)
        radio_frame.pack()
        key_words = ['姓名', '性别', '年龄', '住院号', '床号',
                     '身份证明号', '现住址', '联系人姓名', '联系人电话', '入院时间', '出院时间',
                     '医师', '诊断', '出院诊断',
                     '主诉', '病史', '现病史', 'TPRBP', '入院体检', '入院化验单', '病人简介', '病例特点', '化验单']
        for key_word in key_words:
            v_ = self.patient_info.setdefault(key_word, '无信息')

            tk.Radiobutton(radio_frame,
                           variable=self.flag,
                           text='%s：%s' % (key_word,
                                           v_ if key_word not in ['病史', '主诉', '现病史', '入院体检', 'TPRBP',
                                                                  '入院化验单', '病例特点', '化验单'] else '%s...%s' % (
                                               v_[:10], v_[-10:])),
                           value=v_, command=self.on_select).pack(
                anchor=tk.W,
                padx=10
            )
        for idx, v in enumerate(self.patient_info.setdefault('诊疗计划', [])):
            tk.Radiobutton(radio_frame,
                           variable=self.flag,
                           text='%s：%s' % ('诊疗计划%s' % (idx + 1), '%s...' % v[:20]),
                           value=v, command=self.on_select).pack(
                anchor=tk.W,
                padx=10
            )

        btn_frame = tk.Frame(self)
        btn_frame.pack()

        btn_dif_diagnosis = tk.Button(btn_frame, text='鉴别诊断', command=self.dif_diagnosis, width=12, height=1,
                                      activebackground='grey',
                                      relief='groove')
        btn_dif_diagnosis.pack(side=tk.LEFT, padx=5)

        btn_zz = tk.Button(btn_frame, text='主治查房', command=self.zz, width=12, height=1, activebackground='grey',
                           relief='groove')
        btn_zz.pack(side=tk.LEFT, padx=5)

        btn_zr = tk.Button(btn_frame, text='主任查房', command=self.zr, width=12, height=1, activebackground='grey',
                           relief='groove')
        btn_zr.pack(side=tk.LEFT, padx=5)

        btn_cancel = tk.Button(self, text='退出', command=self.cancel, width=12, height=1, activebackground='grey',
                               relief='groove')
        btn_cancel.pack(side=tk.BOTTOM)

    def on_select(self):
        pyperclip.copy(self.flag.get())

    def cancel(self):
        self.destroy()

    def dif_diagnosis(self):
        dif_diagnosis_window = DifDiagnosis()
        self.wait_window(dif_diagnosis_window)

    def zz(self):
        mod = "今日查房，患儿，查体：%s %s 张伟东主治医师查房仔细询问病史：%s %s 入院查体：%s %s 辅助检查：%s 根据以上资料，张伟东主治医师考虑诊断为%s 应与相鉴别。鉴别内容：。治疗：继续%s 嘱合理饮食，避免受凉。观察病情变化。指示已执行。"
        result = mod % (
            self.patient_info.setdefault('TPRBP', '无信息'),
            self.patient_info.setdefault('入院体检', '无信息'),
            self.patient_info.setdefault('病人简介', '无信息'),
            self.patient_info.setdefault('病例特点', '无信息'),
            self.patient_info.setdefault('TPRBP', '无信息'),
            self.patient_info.setdefault('入院体检', '无信息'),
            self.patient_info.setdefault('入院化验单', '无信息'),
            self.patient_info.setdefault('诊断', '无信息'),
            self.patient_info.setdefault('诊疗计划', '无信息')[1]
        )
        pyperclip.copy(result)

    def zr(self):
        mod_zr = "汇报病史：%s %s 入院查体%s %s %s 入院给予%s 陈芳副主任医师查房：%s %s 辅助检查：%s 目前诊断考虑：%s 需与鉴别，鉴别内容：治疗上继续%s 嘱加强护理，避免受凉，观察病情变化。指示已执行。"
        result_zr = mod_zr % (
            self.patient_info.setdefault('病人简介', '无信息'),
            self.patient_info.setdefault('病例特点', '无信息'),
            self.patient_info.setdefault('TPRBP', '无信息'),
            self.patient_info.setdefault('入院体检', '无信息'),
            self.patient_info.setdefault('入院化验单', '无信息'),
            self.patient_info.setdefault('诊疗计划', '无信息')[1],

            self.patient_info.setdefault('TPRBP', '无信息'),
            self.patient_info.setdefault('入院体检', '无信息'),
            self.patient_info.setdefault('化验单', '无信息'),
            self.patient_info.setdefault('诊断', '无信息'),
            self.patient_info.setdefault('诊疗计划', '无信息')[1],
        )
        pyperclip.copy(result_zr)


class MainWindow(tk.Tk):
    def __init__(self):
        self.text_path = ''
        super().__init__()
        # self.wm_attributes('-topmost', 1)

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 600
        wh = 150
        self.geometry(
            "%dx%d+%d+%d" %
            (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('懒才是王道！     -v2.0 by cbl')
        self.flag = tk.StringVar()
        self.flag.set('病人信息')
        radio_frame = tk.Frame(self)
        radio_frame.pack()
        tk.Radiobutton(radio_frame, variable=self.flag, text='病人信息', value='病人信息').pack(
            side=tk.LEFT)
        tk.Radiobutton(radio_frame, variable=self.flag, text='交班', value='交班').pack(
            side=tk.LEFT)
        tk.Radiobutton(radio_frame, variable=self.flag, text='医保', value='医保').pack(
            side=tk.LEFT)

        tk.Radiobutton(radio_frame, variable=self.flag, text='出入院', value='出入院',
                       ).pack(side=tk.LEFT)

        self.info = tk.StringVar()
        self.info.set('请输入住院号或放入txt文件')

        self.f = tk.Frame(self)
        self.f.pack()

        self.info_label = tk.Label(self.f, textvariable=self.info, font=('微软雅黑', 10), )

        self.info_label.pack()
        self.pid = tk.StringVar()
        self.pid.set('21000000 21000001')
        self.pid_e = tk.Entry(self.f, width=60, textvariable=self.pid, relief='groove',
                              font=('微软雅黑', 10),
                              selectbackground='brown', )

        windnd.hook_dropfiles(self.pid_e.winfo_id(), self.fuc)
        self.pid_e.bind('<FocusIn>', self.on_select)
        self.pid_e.focus_set()
        self.pid_e.pack()

        btn_frame = tk.Frame(self)
        btn_frame.pack(pady=10)
        btn_ok = tk.Button(btn_frame, text='确 定', width=12, height=1, activebackground='grey',
                           relief='groove')
        btn_ok.bind('<ButtonRelease-1>', self.submit)
        btn_ok.pack(side=tk.LEFT)
        btn_cancel = tk.Button(btn_frame, text='取消', command=self.cancel, width=12, height=1, activebackground='grey',
                               relief='groove')
        btn_cancel.pack(side=tk.RIGHT)

    def submit(self, event):
        try:

            result_json = {}
            pid = self.pid.get().strip()
            if pid:
                pid_list = pid.split()
                if pid_list[0].isdigit():
                    lines = pid_list

                else:
                    with open(pid, 'r', ) as f:
                        lines = f.readlines()

                for line in lines:
                    if not line.isdigit():
                        line = line.split()[1].strip()

                    if line.isdigit():

                        self.info_label['fg'] = 'blue'
                        self.info.set('正在查询：【%s】' % line)
                        self.update()

                        query_app = AcquireInfoTotal(line)
                        query_list = ['病程记录', 'LIS报告单']
                        pool = Pool(3)
                        query_result = pool.map(query_app.query_content, query_list)
                        query_dic = {}
                        for each_result in query_result:
                            query_dic.update(each_result)
                        data_resolved = DataResolver(query_app.pid)
                        data_resolved.record_resolve(query_dic)

                        if data_resolved.patient_info:
                            result_json[line] = data_resolved.patient_info

                if result_json:
                    self.info_label['fg'] = 'green'
                    self.info.set('查询结束，将自动打开查询结果，请慢用^_^')
                    self.update()

                    if self.flag.get() == '医保':
                        for v in result_json.values():
                            save_to_word(v)
                            print_file(os.path.abspath('.\\mydocx\\bcnotification.docx'))

                    elif self.flag.get() == '交班':
                        to_word(result_json)
                    elif self.flag.get() == '出入院':
                        in_and_out(result_json)
                    elif self.flag.get() == '病人信息':
                        for v in result_json.values():
                            patient_info_app = PatientInfo(v)
                            self.wait_window(patient_info_app)



            else:
                self.info_label['fg'] = 'red'
                self.info.set('住院号无效！')

        except PermissionError:
            self.info_label['fg'] = 'red'
            self.info.set('运行出错：临时文件被占用！\n请关闭程序自动打开的所有word文件后重试！')
            self.pid.set('')
        except ValueError:
            self.info_label['fg'] = 'red'
            self.info.set('住院号无效！')
            self.pid.set('')

        # except Exception as e:
        #     self.info_label['fg'] = 'red'
        #     self.info.set('运行出错：%s\n请检查后重试！' % e)
        #     self.pid.set('')

    def on_select(self, event):
        # event.widget 即触发事件的控件，可以直接用它的方法如.select_range()等
        event.widget.select_range(0, tk.END)

    def cancel(self):
        try:
            if os.path.isdir('.\\temp\\'):
                shutil.rmtree('.\\temp\\')
            self.destroy()
        except PermissionError:
            self.info_label['fg'] = 'red'
            self.info.set('无法关闭程序：临时文件被占用！\n请关闭程序自动打开的所有word文件后重试！')

    def fuc(self, l):
        self.pid_e.delete(0, 'end')
        for i in l:
            self.pid_e.insert("end", i.decode("gbk") + '\n')


if __name__ == '__main__':
    a = MainWindow()
    a.mainloop()
